#include "server.h"
#include <iostream>

std::map<int,SocketClient *> Server::sVector;
std::map<int,simuladores> Server::sMap;
std::map<QString,wells> Server::wMap;
pthread_mutex_t Server::mutex;

void Server::setStats() {
	char buff[100];
	sprintf(buff,"PORTA %i CONECCOES %i",tcpServer->serverPort(),Server::sVector.size());
	statusLabel->setText(buff);
}

Server::Server(QWidget *parent)
    : QDialog(parent)
{
	pthread_mutex_init(&mutex,NULL);
	statusLabel = new QLabel;
	quitButton = new QPushButton(tr("Quit"));
	quitButton->setAutoDefault(false);
	tcpServer = new QTcpServer(this);
	
	if (!tcpServer->listen(QHostAddress::Any,8000)) {
		close();
		return;
	}
	connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));

	connect(tcpServer, SIGNAL(newConnection()), this, SLOT(acceptNewConnection()));

	QHBoxLayout *buttonLayout = new QHBoxLayout;
	buttonLayout->addStretch(1);
	buttonLayout->addWidget(quitButton);
	buttonLayout->addStretch(1);

	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->addWidget(statusLabel);
	mainLayout->addLayout(buttonLayout);
	setLayout(mainLayout);
	numberOfConnections = 0;
	setWindowTitle(tr("Fortune Server"));
	setStats(); 
	d = new deamon();
	d->start(100);
}

void Server::acceptNewConnection() {
	SocketClient * mSocket = new SocketClient;
	mSocket->sck = tcpServer->nextPendingConnection();
	mSocket->sck->setParent(NULL);
	mSocket->id = numberOfConnections;	
	connect(mSocket->sck, SIGNAL(readyRead()), this, SLOT(readData()));	
	connect(mSocket->sck, SIGNAL(disconnected()),
			this, SLOT(deleteSocket()));
	sVector[mSocket->id] = mSocket;

	numberOfConnections++;
	setStats();
}

void Server::deleteSocket() {
	std::map<int,SocketClient *>::iterator begin;
	printf("DELETANDO UM SOCKET2\n");
	for(begin = sVector.begin(); begin != sVector.end(); begin++){
		if((*begin).second->sck->state() == QAbstractSocket::UnconnectedState){					
			sVector.erase(begin);
			begin->second->id = -1;
			/*while(begin->second->tVector.size() != 0) {
				begin->second->tVector.back()->wait();
				begin->second->tVector.pop_back();
				delete begin->second->tVector.back();
			}*/
			//QTimer::singleShot(0,(*begin).second->sck,SLOT(deleteLater()));
			delete((*begin).second);
			break;	
		}
	}	
	setStats();	
}

void Server::readDataSlot() {
}
void Server::readData() {
	QStringList frame;
	QString Par;
	
	std::map<int,SocketClient *>::iterator begin;
	for(begin = sVector.begin(); begin != sVector.end(); begin++){
		QDataStream in((*begin).second->sck);
		in.setVersion(QDataStream::Qt_4_0);
		if(in.atEnd())
			continue;
	    in >> frame;
	    break;
	}

	if(begin == sVector.end())
		return;
	printf("BLOQUEADO\n\n");
	begin->second->addRequest(frame);
	printf("LIBERADO\n\n");
	readData();
}



